package cn.cooode.activityTools.service.impl;

import cn.cooode.activityTools.dao.ActivityDao;
import cn.cooode.activityTools.dao.EnrollDao;
import cn.cooode.activityTools.entity.Activity;
import cn.cooode.activityTools.entity.Pager;
import cn.cooode.activityTools.service.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class ActivityServiceImpl implements ActivityService {

    @Autowired
    private ActivityDao activityDao;
    @Autowired
    private EnrollDao enrollDao;

    public Page<Activity> getPager(int page, int size) {
        return activityDao.findByActivityCheck_Pass(true, PageRequest.of(page, size));
    }

    @Override
    public List<Activity> findAll() {
        return activityDao.findByActivityCheck_Pass(true);
    }

    public Page<Activity> getPagerByCategory(Long categoryId, int page, int size) {
        return activityDao.findByCategory_IdAndActivityCheck_Pass(categoryId, true, PageRequest.of(page, size));
    }

    public Activity get(Long id) {
        return activityDao.findById(id).get();
    }

    public Page<Activity> getEnrolled(Long userId, int page, int size) {
        return activityDao.findByIdIn(enrollDao.findByUser_Id(userId).stream().map(enroll -> enroll.getActivity().getId()).collect(Collectors.toList()), PageRequest.of(page, size));
    }

    public Page<Activity> getPassed(Long userId, int page, int size) {
        return activityDao.findByIdInAndStartTimeIsAfter(enrollDao.findByUser_Id(userId).stream().map(enroll -> enroll.getActivity().getId()).collect(Collectors.toList()), new Date(), PageRequest.of(page, size));
    }

    public Page<Activity> getPublished(Long userId, int page, int size) {
        return activityDao.findByAuthor_Id(userId, PageRequest.of(page, size));
    }

    public Activity save(Activity activity) {
        return activityDao.save(activity);
    }

}
